<template>
  <div class="shopping">
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="checkAll" />全选/全不选</th>
          <th>书籍名称</th>
          <th>出版日期</th>
          <th>价格</th>
          <th>数量</th>
          <th>删除</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in books" :key="index">
          <td><input type="checkbox" v-model="checkArr[index]" /></td>
          <td>{{ item.name }}</td>
          <td>{{ item.date }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="addOrSub(index, -1)">-</button>
            {{ item.count }}
            <button @click="addOrSub(index, 1)">+</button>
          </td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="6">总价：{{ total }}元</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  name: 'free',
  data() {
    return {
      books: [
        { name: '算法导论', date: '2007-9', price: 100, count: 1 },
        { name: 'UNIX编程艺术', date: '2027-9', price: 120, count: 3 },
        { name: 'Vue程序设计', date: '2017-9', price: 60, count: 1 },
        { name: '颈椎康复', date: '2009-9', price: 30, count: 2 }
      ],
      checkArr: []
    }
  },
  created() {
    this.checkArr = this.books.map(() => false)
  },
  methods: {
    addOrSub(i, val) {
      if (this.books[i].count == 1 && val == -1) return
      this.books[i].count += val
    },
    del(i) {
      this.books.splice(i, 1)
      this.checkArr.splice(i, 1)
    }
  },
  computed: {
    total() {
      return this.books.reduce((pre, curr, index) => pre + (this.checkArr[index] ? curr.price * curr.count : 0), 0)
    },
    checkAll: {
      get() {
        return !this.checkArr.includes(false)
      },
      set(val) {
        this.checkArr = this.checkArr.map(() => val)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.shopping {
  width: 600px;
  margin: 50px auto;
  // background-color: skyblue;
  text-align: center;
}
h1 {
  font-size: 26px;
  font-weight: 700;
  padding: 20px 0;
}
table {
  min-width: 600px;
}
table,
th,
td {
  border: 1px solid #000;
}
th,
td {
  padding: 10px;
}
th {
  font-size: 18px;
  font-weight: 700;
}
</style>
